package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.entity.Brand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.dto.BrandDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;


import java.util.List;

@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    /*添加品牌*/
    @Transactional
    public void addBrand(BrandDTO brandDTO, List<Long> cids) {
        /*进行对象属性之间的赋值*/
        Brand brand = BeanHelper.copyProperties(brandDTO, Brand.class);

        brand.setId(null);

        /*新增品牌，自带主键回显功能*/
        int count = brandMapper.insert(brand);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_BRAND_FAIL);
        }

        /*增加品牌与分类的关联*/
        count = brandMapper.insertCategoryBrand(brand.getId(), cids);
        if (count != cids.size()) {
            throw new LyException(ExceptionEnum.INSERT_BRANDCATEGORY_FAIL);
        }

    }

    /*修改品牌对应的分类*/
    @Transactional
    public void updateBrand(BrandDTO brandDTO, List<Long> cids) {
        Brand brand = BeanHelper.copyProperties(brandDTO, Brand.class);
        /*更新品牌数据,只更新不为空的字段
        * 使用updateByPrimaryKeySelective的话，如果把信息去掉，就无法修改成功
        因为updateByPrimaryKeySelective默认修改不为空的值 */
        int number = brandMapper.updateByPrimaryKey(brand);
        if (number != 1) {
            throw new LyException(ExceptionEnum.UPDATE_BRAND_FAIL);
        }
        //删除与该品牌相关联的种类
        brandMapper.deleteCategoryByBrandId(brand.getId());

        //添加关联
        Integer count = brandMapper.insertCategoryBrand(brand.getId(), cids);
        if (count != cids.size()) {
            // 新增失败，抛出异常
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    //自己写的品牌查询,返回品牌数据以及总页数  key= & sortBy=id &desc=false
    public PageResult<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key, String sortBy, Boolean desc) {
        //先处理分页
        // PageHelper首先将前端传递的参数保存到page这个对象中，
        // 接着将page的副本存放入ThreadLoacl中，这样可以保证分页的时候，参数互不影响，
        // 接着利用了mybatis提供的拦截器，取得ThreadLocal的值，重新拼装分页SQL，完成分页

        //总结：分页插件会先将分页条件进行封装，之后在执行第一个查询语句时将分页参数拼接到sql中
        PageHelper.startPage(page, rows);

        //再添加查询条件  此处根据品牌表进行查询
        Example example = new Example(Brand.class);

        //如果查询条件不为空
        if (StringUtils.isNoneBlank(key)) {
            //查询条件，模糊查询name，或查询letter(首字母),将key转换为大写后再进行查询
            example.createCriteria().
                    orLike("name", "%" + key + "%").orEqualTo("letter", key.toUpperCase());
        }

        //如果排序字段不为空,添加排序条件
        if (StringUtils.isNoneBlank(sortBy)) {

            sortBy = sortBy + (desc ? " DESC" : " ASC");
            example.setOrderByClause(sortBy);
        }

        //查询
        List<Brand> brands = brandMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(brands)) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }

        List<BrandDTO> brandDTOS = BeanHelper.copyWithCollection(brands, BrandDTO.class);
        /*解析分页结果*/
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);


        return new PageResult(pageInfo.getTotal(), brandDTOS);
    }

    /*根据品牌id查询品牌*/
    public BrandDTO queryById(Long brandId){
        Brand brand = brandMapper.selectByPrimaryKey(brandId);
        if (brand == null){
            throw new LyException(ExceptionEnum.RESOURCE_NOT_FOUND);
        }
        return BeanHelper.copyProperties(brand,BrandDTO.class);
    }

    /*根据分类id查询品牌列表*/
    public List<BrandDTO> queryBrandsByCategoryId(Long categoryId) {

        List<Brand> brands = brandMapper.queryBrandsByCategoryId(categoryId);
        if (CollectionUtils.isEmpty(brands)){
            throw new LyException(ExceptionEnum.RESOURCE_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(brands,BrandDTO.class);
    }

    /**
     * 删除品牌
     * @param brandId
     * @return
     */
    @Transactional
    public void deleteBrandById(Long brandId) {
        Brand brand = new Brand();
        brand.setId(brandId);

        /*删除品牌*/
        int record = brandMapper.delete(brand);
        if (record != 1){
            throw new LyException(ExceptionEnum.DEFAULT_DELETE_ERROR);
        }


        /*删除品牌与分类的关联，一般一个品牌只会对应一个分类*/
         brandMapper.deleteCategoryByBrandId(brandId);
        if (record != 1){
            throw new LyException(ExceptionEnum.DEFAULT_DELETE_ERROR);
        }


    }

    /**
     * 根据品牌id的集合查询品牌集合
     * @param brandIds
     * @return
     */
    public List<BrandDTO> queryBrandByIds(List<Long> brandIds) {

        List<Brand> brands = brandMapper.selectByIdList(brandIds);
        if (CollectionUtils.isEmpty(brands)){
            throw new LyException(ExceptionEnum.RESOURCE_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(brands,BrandDTO.class);
    }
}
